<?php
require_once 'config.php';

session_start();


if (isset ( $_SESSION ['access_token'] )) {
	
} else {
	$phase = 0;
	if (isset ( $_GET ['code'] )) {
		$phase = 1;
	}
	if ($phase == 0) {
		die ( "restricted access" );
	}
	$code = $_GET ['code'];
	fetchAccessToken($code);
}

function fetchAccessToken($code)	{
	$exchangeUrl = "https://graph.facebook.com/oauth/access_token";
	
	$params = array ();
	$params ['client_id'] = GlobalConfig::$appId;
	$params ['redirect_uri'] = GlobalConfig::$oauth_redirect;
	$params ['client_secret'] = GlobalConfig::$appSecret;
	$params ['code'] = $code;
	
	$ch = curl_init ();
	curl_setopt ( $ch, CURLOPT_URL, $exchangeUrl );
	curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, true );
	curl_setopt ( $ch, CURLOPT_FOLLOWLOCATION, true );
	curl_setopt ( $ch, CURLOPT_POST, 1 );
	curl_setopt ( $ch, CURLOPT_POSTFIELDS, $params );
	curl_setopt ( $ch, CURLOPT_SSL_VERIFYHOST, 1 );
	$result = curl_exec ( $ch );
	
	if (strpos ( $result, "access_token=" ) !== 0) {
		die ( "failed to get access_token: ".$result );
	}
	
	$access_token = str_replace ( "access_token=", "", $result );
	$_SESSION ['access_token'] = $access_token;
	die("access_token is $access_token");
}

function convert_array_to_param($array) {
	$string = "";
	foreach ( $array as $key => $value ) {
		$string .= "$key=$value&";
	}
	$string = rtrim ( $string, "&" );
	return $string;
}
?>

<script>window.close()</script>